const fs = require("fs");
const path = require("path");
const { config } = require("dotenv");
const nodemailer = require("nodemailer");

config({ override: true });

// 请在 .env 中配置用户、密码和服务器
let { MAIL_USER, MAIL_PASS, MAIL_HOST, MAIL_TO_KINDLE } = process.env;

module.exports = dispatchEmail;

function dispatchEmail(filePath) {
  let transport = nodemailer.createTransport({
    host: MAIL_HOST,
    auth: {
      user: MAIL_USER,
      pass: MAIL_PASS,
    },
  });

  let mailOptions = {
    from: MAIL_USER + "@sina.com",
    to: MAIL_TO_KINDLE,
    subject: "book",
    text: "book",
    attachments: [
      {
        filename: path.basename(filePath),
        content: fs.createReadStream(filePath),
      },
    ],
  };

  return transport.sendMail(mailOptions);
}

// let filepath = path.resolve(__dirname, "2023-3-26-NPR.epub");
// dispatchEmail(filepath)
//   .then((info) => console.log("Mail is delevered success!"))
//   .catch((error) => {
//     console.log("----------------------");
//     console.log(error);
//   });
